package com.topisv.tms.service.redis;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.utils.JsonUtil;
//Spring Bean的标识.
@Component
public class RedisEdiOrdenoService {

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	/**
	 * 保存源数据
	 * 
	 * @param ediOrder
	 */
	public void save(final EdiOrder ediOrder) throws Exception {
		redisTemplate.execute(new RedisCallback<EdiOrder>() {
			@Override
			public EdiOrder doInRedis(RedisConnection connection)throws DataAccessException {
				String key = ediOrder.getCustomerCode() + ":ordenos";// hashMap
				JSONObject json=new JSONObject();
				JSONObject j=json.fromObject(ediOrder);
				Map<byte[], byte[]> maps=new HashMap<byte[], byte[]>();
				maps.put(ediOrder.getOrdeno().getBytes(),j.toString().getBytes());
				connection.hMSet(key.getBytes(), maps);
				return null;
			}
		});
	}


	/**
	 * 读取源数据
	 * @param customerCode
	 * @param ordeno
	 * @return
	 */
	public EdiOrder read(final String customerCode, final String ordeno)  throws Exception{
		return redisTemplate.execute(new RedisCallback<EdiOrder>() {
			public EdiOrder doInRedis(RedisConnection connection) {
				byte[] key = (customerCode + ":ordenos").getBytes();// hashMap
				byte[] value = connection.hGet(key, ordeno.getBytes());
				if(value==null){
					return null;
				}
				String ediString=new String(value);
				EdiOrder e = JsonUtil.getEdiOrder(ediString);
				return e;
			}
		});
	}
	
	
}
